#include "../include/login.h"
#include "../include/password.h"

#define rt_delete "用户注销成功" //注销返回值
#define rt_modify "密码修改成功" //修改返回值

//账户系统:进入账户修改系统,可以进行对账号的增删改查
//参数:链表头节点和登录权限
//返回值:0
extern TRAN m_node;//使用其他.c文件中的全局变量
char pas_buff[1024]={0};
int use_system(int client_socket){
	int ch = 0;
	TRAN node;
	while(ch!=-1){
		bzero(&node,sizeof(node));
		//选择菜单
		printf("请选择账户操作:\n1:注销账户\n2:修改账户密码\n");
		printf("其他任意键退出\n");
		scanf("%d",&ch);
		if(ch!=1 && ch!=2){//退出
			break;
		}
		if(m_node.perm==1 && ch==1){
			puts("管理员账户无法注销");
			break;
		}
		switch(ch){
			case 1:
				//注销功能
				printf("请输入账户密码:");
				scanf("%s",node.pas);
				getchar();
				if(strcmp(node.pas,m_node.pas)==0){//判断和旧密码是否相同
					printf("密码正确,输入YES进行账户注销\n");
					scanf("%s",pas_buff);
					if(strcmp(pas_buff,"YES")!=0)
						break;
				}else{
					printf("密码错误,退出注销系统\n");
					break;
				}
				pas_packJson(&node,ch);
				break;
			case 2:
				//修改功能
				printf("请输入账户旧密码");
				scanf("%s",node.pas);
				getchar();
				if(strcmp(node.pas,m_node.pas)!=0){//判断和旧密码是否相同
					printf("密码错误,退出修改系统\n");
					break;
				}
				while(1){
					printf("请输入新密码(至少为3位字符):");
					scanf("%s",node.pas);
					if(strlen(node.pas)<3){
						puts("密码长度不足");
						continue;
					}
					break;
				}
				
				pas_packJson(&node,ch);
				break;
		}
		printf("准备向服务端发送信息:%s\n",pas_buff);
		write(client_socket,pas_buff,strlen(pas_buff));
		
		puts("准备从服务器接收返回值");
		bzero(pas_buff,sizeof(pas_buff));
		sleep(2);
		int num=read(client_socket,pas_buff,1024);
		if(num<=0){
			puts("已超时,未能接收到返回值");
			return -1;
		}else{
			printf("接收到返回值:%s\n",pas_buff);
		}
		if(strcmp(rt_modify,pas_buff)==0){
			strcpy(m_node.pas,node.pas);
			return 1;
		}
		if(strcmp(rt_delete,pas_buff)==0){
			return 2;
		}else if(strcmp("无法注销管理员账户",pas_buff)==0){
			puts("无法注销管理员账户");
		}
	}
	
	return 0;	
}

void pas_packJson(TRAN *node,int sel)
{
	if(sel == 1){//注销
		strcpy(node->order,"delete");
	}else if(sel == 2){//修改
		strcpy(node->order,"modify");
	}
	strcpy(node->name,m_node.name);
	
	cJSON* root = cJSON_CreateObject();
	cJSON* order = cJSON_CreateString(node->order);
	cJSON* name = cJSON_CreateString(node->name);
	cJSON* pas = cJSON_CreateString(node->pas);;
	cJSON* newpas = cJSON_CreateString("");

	cJSON_AddItemToObject(root,"order",order);
	cJSON_AddItemToObject(root,"name",name);
	if(sel==1){//注销
		cJSON_AddItemToObject(root,"pwd",pas);
		cJSON_AddItemToObject(root,"new_pwd",newpas);
	}else if(sel==2){//修改
		cJSON_AddItemToObject(root,"pwd",newpas);
		cJSON_AddItemToObject(root,"new_pwd",pas);
	}
	char *p=pas_buff;
	p=cJSON_Print(root);
	strcpy(pas_buff,p);
	cJSON_Delete(root);
}

